package com.sskj.mine.ui.fragment;


import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppToastInnerCheckUtil;
import com.sskj.lib.util.CommonUtil;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.bean.MainItemBean;
import com.sskj.mine.bean.MineNoticeList;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.http.HttpConfig;
import com.sskj.mine.presenter.MineFragmentPresenter;
import com.sskj.mine.util.DividerGridItemDecoration;
import com.sskj.mine.util.TipMineUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.MINE_FRAGMENT_MAIN)//我的主页
public class MineFragment extends BaseFragment<MineFragmentPresenter> {
    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.mine_setting)
    ImageView mineSetting;
    @BindView(R2.id.ivInto)
    ImageView ivInto;
    @BindView(R2.id.mine_tx)
    ImageView mineTx;
    @BindView(R2.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R2.id.tv_show_position)
    TextView tvShowPosition;
    @BindView(R2.id.mine_tel)
    TextView mineTel;
    @BindView(R2.id.mine_id)
    TextView mineId;
    @BindView(R2.id.login_show)
    LinearLayout loginShow;
    @BindView(R2.id.noLoginShow)
    TextView noLoginShow;
    @BindView(R2.id.ivBack)
    ImageView ivBack;
    private UserData userData;
    private List<MainItemBean> items;
    private MaterialDialog tip;
    private MaterialDialog loginTip;
    private int curLanguagePos = 0;
    private String id;
    private Disposable noticeDispo;
    private MineNoticeList noticeList;

    //
    @Override
    protected int getLayoutId() {
        return R.layout.mine_fragment_main;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser && userViewModel != null) {
            userViewModel.update();
        }
        super.setUserVisibleHint(isVisibleToUser);
    }


    @Override
    public MineFragmentPresenter getPresenter() {
        return new MineFragmentPresenter();
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        tvTitle.setText("我的");
        ivBack.setVisibility(View.GONE);
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 30);
            textView.setTextColor(getResources().getColor(R.color.mine_12243B));
            return textView;
        });
        id = SPUtil.get(SPConfig.ID, "");

        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                updateUI();
            } else {
                userData = null;
                loginShow.setVisibility(View.GONE);
                noLoginShow.setVisibility(View.VISIBLE);
            }
        });
        initItem();
        initRecy();
        ClickUtil.click(noLoginShow, () -> {
            ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
        });
        ClickUtil.click(ivInto, () -> {
            if (userData == null) {
                ToastUtil.showShort("请先完成登录");
                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                return;
            }
            ARouter.getInstance().build(RConfig.MINE_PERSON_CENTER).navigation();  // 个人中心
        });
        ClickUtil.click(mineSetting, () -> {
            if (userData == null) {
                ToastUtil.showShort("请先完成登录");
                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                return;
            }
            ARouter.getInstance().build(RConfig.MINE_SETTING).navigation();  // 设置中心
        });
        userViewModel.update();
    }

    private void initRecy() {
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyclerView.addItemDecoration(new DividerGridItemDecoration(getContext(), getResources().getColor(R.color.mine_E6EBF2), 2, 0));
        SlimAdapter.create().register(R.layout.mine_recy_item_main, new SlimInjector<MainItemBean>() {
            @Override
            public void onInject(MainItemBean data, IViewInjector injector, List payloads) {
                injector
                        .text(R.id.tvTitle, data.getTitle())
                        .image(R.id.ivTitle, data.getIcon());
            }
        }).attachTo(recyclerView).updateData(items);
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
//                    if (position < 6 && position != 4 && userData == null) {
//                        if (loginTip == null) {
//                            loginTip = TipMineUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.mineMineFragment1), App.INSTANCE.getString(R.string.mineMineFragment2), () -> {
//                                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
//                            });
//                        }
//                        loginTip.show();
//                        return;
//                    }
                    switch (position) {
                        case 0:
                            if (userData == null) {
                                ToastUtil.showShort("请先完成登录");
                                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                                return;
                            }
                            ARouter.getInstance().build(RConfig.MINE_SECURITY_CENTER).navigation();  // 安全中心
                            break;
                        case 1:
                            if (userData == null) {
                                ToastUtil.showShort("请先完成登录");
                                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                                return;
                            }
                            ARouter.getInstance().build(RConfig.MINE_VERIFICATION_MENU).navigation();
                            break;
                        case 2:
                            if (userData == null) {
                                ToastUtil.showShort("请先完成登录");
                                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                                return;
                            }
                            ARouter.getInstance().build(RConfig.MINE_WALLET_ADDRESS_MANAGER).navigation();  // 提币地址
                            break;
                        case 3:
                            if (userData == null) {
                                ToastUtil.showShort("请先完成登录");
                                ARouter.getInstance().build(RConfig.MINE_LOGIN).navigation();
                                return;
                            }
                            ARouter.getInstance().build(RConfig.MINE_AGENT_MANAGER).navigation();
//                            if (AppOuterCheckUtil.checkAuth(getActivity(), userData)) {  // 经纪人
//                                if (userData.getIsApplyStatus() == 3) {
//                                    ARouter.getInstance().build(RConfig.MINE_AGENT_MANAGER).navigation();
//                                } else if (userData.getIsApplyStatus() == 1) {
//                                    ARouter.getInstance().build(RConfig.MINE_APPLY_AGENT).navigation();
//                                } else if (userData.getIsApplyStatus() == 2) {//审核
//                                    TipUtil.getTip(getActivity(), getString(R.string.mine_agent_checking_tip), false, () -> {
//
//                                    }).show();
//                                } else if (userData.getIsApplyStatus() == 4) {//拒绝
//                                    TipUtil.getTip(getActivity(), getString(R.string.mine_agent_reject_reason), userData.getInspectStaffReason(), getString(R.string.mine_retry_apply), () -> {
//                                        ARouter.getInstance().build(RConfig.MINE_APPLY_AGENT).navigation();
//
//                                    }).show();
//                                }
//                            }
                            break;
                        case 4:
                            ARouter.getInstance().build(RConfig.MINE_CONTANT_KF).navigation();    // 客服中心
                            break;
                        case 5:
//                            ARouter.getInstance().build(RConfig.MINE_ABOUT_US).navigation();  // 关于我们
                            ARouter.getInstance().build(RConfig.MINE_CONTANCT_US).navigation();  // 联系我们
                            break;
                        case 6:
                            ARouter.getInstance().build(RConfig.GONGGAO_ACTIVITY_MAIN).navigation();
                            break;
                    }
                });
    }

    private void initItem() {
        items = new ArrayList<>();
        items.add(new MainItemBean(R.mipmap.mine_aqzx, "安全中心"));
        items.add(new MainItemBean(R.mipmap.mine_smrz, "实名认证"));
        items.add(new MainItemBean(R.mipmap.mine_tbdz, "提币地址"));
        items.add(new MainItemBean(R.mipmap.mine_wdtg, "我的推广"));
        items.add(new MainItemBean(R.mipmap.mine_lxkf, "联系客服"));
        items.add(new MainItemBean(R.mipmap.mine_gywm, "关于我们"));
    }

    /**
     * 根据用户信息更新页面
     */
    private void updateUI() {
        loginShow.setVisibility(View.VISIBLE);
        noLoginShow.setVisibility(View.GONE);
        ImageUtil.setCircleImage(HttpConfig.BASE_IMG_URL + userData.getHeadUrl(), mineTx);
        mineTel.setText(TextUtils.isEmpty(userData.getTel()) ? CommonUtil.dealEmail(userData.getEmail()) : CommonUtil.dealTel(userData.getTel()));
        mineId.setText("交易ID: " + String.valueOf(userData.getAccount()));

    }

    /**
     * 判断用户实名认证
     */
    public void checkIdent() {
        switch (userData.getStatus()) {
            case 3:
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mineSecurityCenterActivity13));
                break;
            case 2:
                showApplyTip(App.INSTANCE.getString(R.string.mineSecurityCenterActivity14), false);
                break;
            default:
                ARouter.getInstance().build(RConfig.MINE_CERTIFICATION).navigation();
                break;
        }
    }

    /**
     * 判断用户实名认证弹窗
     */
    private void showApplyTip(String msg, boolean status) {
        if (tip == null) {
            tip = TipMineUtil.getTip(getContext(), App.INSTANCE.getString(R.string.mineSecurityCenterActivity15),
                    msg,
                    App.INSTANCE.getString(R.string.mineSecurityCenterActivity17),
                    () -> {
                        tip.dismiss();
                        if (status) {
                            ARouter.getInstance().build(RConfig.MINE_CERTIFICATION).navigation();
                        }
                    });
        }
        tip.show();
    }

    public void setNotice(List<MineNoticeList> notice) {
        if (tvNotice != null) {
            if (notice.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .onBackpressureDrop()
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                noticeList = notice.get((int) (i % notice.size()));
                                tvShowPosition.setText(String.valueOf(i % notice.size() + 1) + "/" + notice.size());
                                tvNotice.setText(noticeList.getTitle());
                                ClickUtil.click(tvNotice, () -> {
                                    ARouter.getInstance().build(RConfig.APP_MSG_DETAIL).withString(Constans.ID, noticeList.getId()).navigation();
                                });
                            }
                        }, System.out::println);
            }
        }
    }

    @Override
    public void initData() {
        mPresenter.getNotice();
    }
}
